package com.gandong8.derby.core.util;

import com.gandong8.derby.core.exception.ErrorException;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestUtil {


    public static String getIp() {
        HttpServletRequest request = RequestUtil.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inetAddress != null;
                ip= inetAddress.getHostAddress();
            }
        }
        return ip;
    }

    public  static void clearSession(String attr){
        HttpServletRequest request = RequestUtil.getRequest();
        request.getSession().removeAttribute(attr);
    }

    public  static void setSession(String attr,Object obj){
        HttpServletRequest request = RequestUtil.getRequest();
        request.getSession().setAttribute(attr, obj);
    }

    public  static Object getSession(String attr){
        HttpServletRequest request = RequestUtil.getRequest();
        return  request.getSession().getAttribute(attr);
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

    public static String getPath() {
        HttpServletRequest request = RequestUtil.getRequest();
        return request.getServletPath();
    }

    public static Map<String, String> getParameters() {
        HashMap<String, String> values = new HashMap<>();
        HttpServletRequest request = RequestUtil.getRequest();
        Enumeration enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String paramName = (String) enums.nextElement();
            String paramValue = request.getParameter(paramName);
            values.put(paramName, paramValue);
        }
        return values;
    }

    public static String getHeader(String key) {
        HttpServletRequest request = RequestUtil.getRequest();
        return request.getHeader(key);
    }

    public static Map<String, String> getHeaders() {
        Map<String, String> map = new HashMap<>();
        HttpServletRequest request = RequestUtil.getRequest();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    public static void output(String data) {
        HttpServletResponse response = getResponse();
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(data);
            writer.close();
        } catch (Exception e) {
            throw new ErrorException(e.getMessage());
        }
    }

    public static String getCookieValue(String name) {
        HttpServletRequest request = RequestUtil.getRequest();
        Cookie[] cookies = request.getCookies();
        if(cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
